import mongoose from 'mongoose'
// 表结构对象
const tokenSchema = new mongoose.Schema(
  {
    access_token: String,
    expires_in: Number,
    refresh_token: String,
    openid: String,
    scope: String,
    create_at: Number,
  },
  {
    timestamps: {
      createdAt: 'createTime',
      updatedAt: 'updateTime',
    },
  }
)
// 自定义获取token静态方法
tokenSchema.statics.getToken = async function (openid) {
  console.log('测试openid:', openid)
  return await this.findOne({ openid })
}
// 自定义存储token静态方法
tokenSchema.statics.setToken = async function (openid, token) {
  // 有则更新，无则添加
  console.log('测试token:', token)
  const query = { openid }
  const options = { upsert: true }
  return await this.updateOne(query, token, options)
}
// 创建模型类并导出
module.exports = mongoose.model('Token', tokenSchema)
